package com.monkey.tensquare.article.controller;

import com.monkey.tensquare.article.entity.Article;
import com.monkey.tensquare.article.service.ArticleService;
import entity.Result;
import entity.StateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @PostMapping
    public Result add(@RequestBody Article article){
        try {
            articleService.add(article);
            return new Result(StateCode.OK,true,"添加文章成功！",null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StateCode.ERROR,false,"添加文章失败！",null);
        }
    }
    @GetMapping
    public Result findAll(){
        try {
            List<Article> articleList = articleService.findAll();
            return new Result(StateCode.OK,true,"查询文章列表成功！",articleList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StateCode.ERROR,false,"查询文章列表失败！",null);
        }
    }
    @GetMapping("{articleId}")
    public Result findById(@PathVariable String articleId){
        try {
            Article article = articleService.findById(articleId);
            return new Result(StateCode.OK,true,"查询文章成功！",article);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StateCode.ERROR,false,"查询文章失败！",null);
        }
    }
    @PutMapping("{articleId}")
    public Result update(@PathVariable String articleId, @RequestBody Article article){
        try {
            articleService.update(articleId,article);
            return new Result(StateCode.OK,true,"修改文章成功！",null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StateCode.ERROR,false,"修改文章失败！",null);
        }
    }
    @DeleteMapping("{articleId}")
    public Result delete(@PathVariable String articleId){
        try {
            articleService.delete(articleId);
            return new Result(StateCode.OK,true,"修改文章成功！",null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StateCode.ERROR,false,"修改文章失败！",null);
        }
    }
}
